import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';

class TerminalAddressIconToImage extends StatefulWidget{
  // 组件的key
  final GlobalKey globalKeys;
  TerminalAddressIconToImage({this.globalKeys,});
  @override
  _TerminalAddressIconToImageState createState() => _TerminalAddressIconToImageState();

}

class _TerminalAddressIconToImageState extends State<TerminalAddressIconToImage>{

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: widget.globalKeys,
      child:  Container(
        child: Image.asset(
          "images/icon_terminal_position.png",
          width: 30,
        ),
      ),
    );
  }
}

// 单例 用于获取图片
class GetWidgetToImage{
  static GlobalKey _globalKeys;
  static GetWidgetToImage _etWidgetToImage;
  // 存放图片的路径
  String _path = "/widget to img/";
  static GetWidgetToImage getInstance(globalKey){
    if (_etWidgetToImage == null) {
      _etWidgetToImage = new GetWidgetToImage();
    }
    _globalKeys = globalKey;
    return _etWidgetToImage;
  }

  // 获取路径
  Future<String> _getPath() async {
    String _filePath = (await getExternalStorageDirectory()).path + _path;
    // 路径不存在则创建
    if (!await Directory(_filePath).exists()) {
      Directory(_filePath).create();
    }
    return _filePath;
  }

  // 获取unit8
  Future<Uint8List> getUint8List() async{
    RenderRepaintBoundary boundary = _globalKeys.currentContext.findRenderObject();
      ui.Image image = await boundary.toImage(pixelRatio: window.devicePixelRatio,);
      ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      return byteData.buffer.asUint8List();
  }

  // 返回 文件
  Future<File>  getFile() async {
    String _filePath  = await _getPath();
    return File(_filePath + DateTime.now().millisecondsSinceEpoch.toString() + ".png").writeAsBytes(await getUint8List());
  }

  // 返回Base64流
  Future<String> getByte64() async{
    return base64Encode(await getUint8List());
  }
}